package com.fuego.creditsystemcommodity.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuego.creditsystemcommodity.mapper.HotelMapper;
import com.fuego.creditsystemcommodity.service.IHotelService;
import jakarta.annotation.Resource;
import org.example.dto.Result;
import org.example.entity.Hotel;
import org.example.utils.CacheClient;
import org.example.utils.SystemConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

import static org.example.utils.RedisConstants.*;


@Service
public class HotelServiceImpl extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;
    @Override
    public Result queryById(Long id) {

        //逻辑过期解决缓存穿透

        Hotel hotel =cacheClient
                .queryWithLogicalExpire(CACHE_OWNER_KEY,LOCK_OWNER_KEY,id, Hotel.class,this::getById,CACHE_OWNER_TTL,TimeUnit.MINUTES);
        if(hotel==null)
        {
            return Result.fail("店铺不存在！");
        }
        // 返回
        return Result.ok(hotel);
    }

    @Override
    @Transactional
    public Result update(Hotel hotel) {
        Long id= hotel.getId();
        if(id==null)
        {
            return Result.fail("商铺id不能为空");
        }
        //1更新数据库
        updateById(hotel);
        String key=CACHE_OWNER_KEY+hotel.getId();
        stringRedisTemplate.delete(key);
        // 2删除缓存
        return Result.ok();
    }

    @Override
    public Result queryByType(Integer typeId, Integer current) {
        //1判断是否需要根据坐标查询

        Page<Hotel> page=query()
                .eq("type_id",typeId)
                .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
        //返回数据
        return Result.ok(page.getRecords());
    }
}
